package com.cn.longdistancebusstation.scenic;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.MainActivity;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.annotation.LoginStatus;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.callback.OnTicketListener;
import com.cn.longdistancebusstation.fragment.OrderNoteFragment;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.ListResult;
import com.cn.longdistancebusstation.model.ListResultIII;
import com.cn.longdistancebusstation.model.Scenic;
import com.cn.longdistancebusstation.model.ScenicDetails;
import com.cn.longdistancebusstation.model.Ticket;
import com.cn.longdistancebusstation.registerAndLogin.LoginActivity;
import com.cn.longdistancebusstation.scenic.order.SubmitOrderActivity;
import com.cn.longdistancebusstation.util.ToolUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/3/28.
 */

public class ScenicDetailsActivity extends BaseActivity implements View.OnClickListener,OnRecyclerViewItemClickListener,OnTicketListener {
    private ImageView mScenicImageView;
    private TextView mScenicNameTextView;
    private TextView mScenicPlaceTextView;
    private ImageView mScenicIntroduceImageView;
    private RecyclerView mRecyclerView;
    private ScenicDetailAdapter mScenicDetailAdapter;
    private Scenic mScenic;
    private List<Ticket> mTickets=new ArrayList<>();
    private String preDaysNum,delayDay,delayType,limitNumUp,limitNumLow,note,refund,preHours,UUrefund_audit;
    private ScenicDetails mScenicDetail;
    private String orderNote;
    private String scenicIntroduce;
    private String trafficInfo;
    private String ticketPrice;
    private String strStart="http";
    private String scenicPath="http://www.12301.cc/";
    private TextView mScenicIntroduceTextView;
    private String mUUjtypeString;
    private String mUUaddressString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scenic_details2);
        Intent in=getIntent();
        mScenic=(Scenic)in.getSerializableExtra("scenicInfo");
        getTitleTextView().setText("详情");
        initView();
        getScenicIntroduction();
    }

    private void initView() {
        mScenicImageView=(ImageView)findViewById(R.id.imageView_scenic);
        if(mScenic.getUUimgpath().startsWith(strStart)){
            Picasso.with(ScenicDetailsActivity.this).load(mScenic.getUUimgpath()).placeholder(R.mipmap.pre_loading)
                    .error(R.mipmap.pre_loading).noFade().into(mScenicImageView);
        }else{
            Picasso.with(ScenicDetailsActivity.this).load(scenicPath+mScenic.getUUimgpath()).placeholder(R.mipmap.pre_loading)
                    .error(R.mipmap.pre_loading).noFade().into(mScenicImageView);
            Log.d("图片地址",scenicPath+mScenic.getUUimgpath());
        }
        mScenicNameTextView=(TextView)findViewById(R.id.textView_scenic_name);
        mScenicPlaceTextView=(TextView)findViewById(R.id.textView_scenic_place);
        mScenicIntroduceTextView=(TextView)findViewById(R.id.textView_scenic_introduction);
        mScenicIntroduceTextView.setOnClickListener(this);
        mScenicIntroduceImageView=(ImageView)findViewById(R.id.imageView_scenic_introduction);
        mScenicIntroduceImageView.setOnClickListener(this);
        mRecyclerView=(RecyclerView)findViewById(R.id.scenic_ticket_type);
        mScenicDetailAdapter=new ScenicDetailAdapter();
        mRecyclerView.setAdapter(mScenicDetailAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mScenicDetailAdapter.setmOnRecyclerViewItemClickListener(this);
        mScenicDetailAdapter.setmOnTicketListener(this);

    }
    /*
    * 获取景点下的门票列表
    * */
    private void getTicket() {
        mTickets.clear();
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResult<Ticket>> call=httpService.getTicket(mScenic.getUUid(),"");
        call.enqueue(new Callback<ListResult<Ticket>>() {
            @Override
            public void onResponse(Call<ListResult<Ticket>> call, Response<ListResult<Ticket>> response) {
                hideHud();
                ListResult result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()) {
                        Gson gson = new Gson();
                        String strBody = gson.toJson(result.getBody().getData());
                        Log.d("数据", strBody);
                        Type type = new TypeToken<List<Ticket>>() {
                        }.getType();
                        mTickets = gson.fromJson(strBody, type);
                        Log.d("门票数量", String.valueOf(mTickets.size()));
                        mScenicDetailAdapter.notifyDataSetChanged();
                        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                        editor.putString("scenicId", mScenic.getUUid());
                        editor.commit();
                    }

                }else{

                }


            }

            @Override
            public void onFailure(Call<ListResult<Ticket>> call, Throwable t) {
                hideHud();
                Toast.makeText(ScenicDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

    }
    private void getScenicIntroduction() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResultIII<ScenicDetails>> call=httpService.getScenicDetails(mScenic.getUUid());
        call.enqueue(new Callback<ListResultIII<ScenicDetails>>() {
            @Override
            public void onResponse(Call<ListResultIII<ScenicDetails>> call, Response<ListResultIII<ScenicDetails>> response) {
                hideHud();
                ListResultIII result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()) {
                        Gson gson = new Gson();
                        Map<String, List<ScenicDetails>> scenicMap = result.getBody().getData();
                        List<ScenicDetails> list = scenicMap.get("Rec");

                        Type type = new TypeToken<ScenicDetails>() {
                        }.getType();
                        String strScenicJSON = new Gson().toJson(list.get(0));
                        mScenicDetail = gson.fromJson(strScenicJSON, type);
                        orderNote=mScenicDetail.getUUjqts();
                        scenicIntroduce=mScenicDetail.getUUbhjq();
                        trafficInfo=mScenicDetail.getUUjtzn();
                        mUUjtypeString=mScenicDetail.getUUjtype();
                        mUUaddressString=mScenicDetail.getUUaddress();
                        mScenicNameTextView.setText(mScenic.getUUtitle()+"("+mUUjtypeString+")");
                        mScenicPlaceTextView.setText(mUUaddressString);
                        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                        editor.putString("note", mScenicDetail.getUUjqts());
                        editor.commit();
                        //
                        getTicket();
                    }

                }

            }

            @Override
            public void onFailure(Call<ListResultIII<ScenicDetails>> call, Throwable t) {
                hideHud();
                Toast.makeText(ScenicDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.textView_scenic_introduction:
                Intent intent=new Intent(ScenicDetailsActivity.this,ScenicIntroductionActivity.class);
                intent.putExtra("orderNote",orderNote);
                intent.putExtra("scenicIntroduce",scenicIntroduce);
                intent.putExtra("trafficInfo",trafficInfo);
                startActivity(intent);
                break;
            case R.id.imageView_scenic_introduction:
                Intent in=new Intent(ScenicDetailsActivity.this,ScenicIntroductionActivity.class);
                in.putExtra("orderNote",orderNote);
                in.putExtra("scenicIntroduce",scenicIntroduce);
                in.putExtra("trafficInfo",trafficInfo);
                startActivity(in);
                break;

        }

    }

    @Override
    public void onClick(int position) {

    }

    @Override
    /*
    * 提交订单
    * */
    public void onClickInnerCtrl(int position) {
        if(GlobalVariable.getLoginStatus() == LoginStatus.STATUS_LOGIN){
            Intent in=new Intent(ScenicDetailsActivity.this, SubmitOrderActivity.class);
            in.putExtra("scenicName",mScenic.getUUtitle());
            in.putExtra("scenicId",mScenic.getUUid());
            in.putExtra("scenicImage",mScenic.getUUimgpath());
            in.putExtra("ticketInfo",mTickets.get(position));
            startActivity(in);
        }else{
            Intent intent = new Intent(ScenicDetailsActivity.this, LoginActivity.class);
            startActivity(intent);
        }

    }

    @Override
    public void onClickCoupon(int position) {

    }

    @Override
    public void onClickCheckBox(int position) {

    }

    @Override
    public void onClickTicket(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_ticket_illustrates, null);
        final TextView mPayTimeTextView=(TextView)view.findViewById(R.id.textView_pay_time_detail);
        final TextView mPeriodOfValidatyTextView=(TextView)view.findViewById(R.id.textView_period_od_validity_details);
        final TextView mPayLimitTextView=(TextView)view.findViewById(R.id.textView_buy_limit_details);
        final TextView mScenicIllustrateTextView=(TextView)view.findViewById(R.id.textView_scenic_illustrate_details);
        final TextView mRefundTextView=(TextView)view.findViewById(R.id.textView_refund_details);
        ImageView cancle = (ImageView) view.findViewById(R.id.cancle_pop);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
//        popupWindow.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
        View parent = LayoutInflater.from(this).inflate(R.layout.scenic_ticket_order_recycle, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        preDaysNum=mTickets.get(position).getUUddays();
        Log.d("preDaysNum",preDaysNum);
        delayDay=mTickets.get(position).getUUdelaydays();
        preHours=mTickets.get(position).getUUdhour();
        Log.d("delayDay",delayDay);
        delayType=mTickets.get(position).getUUdelaytype();
        Log.d("delayType",delayType);

        //限购政策
        int upLimit = mTickets.get(position).getUUbuy_limit_up();
        int lowLimit = mTickets.get(position).getUUbuy_limit_low();
        String strLowLimitDesc = lowLimit>0 ? lowLimit+"张起购" : "";
        String strUpLimitDesc = upLimit>0 ? "一次最多购买"+upLimit+"张" : "";
        mPayLimitTextView.setText(strLowLimitDesc + " " + strUpLimitDesc);
        //
        note=mTickets.get(position).getUUnotes();
        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
        editor.putString("scenicOrderNote", note);
        editor.commit();
        Log.d("note",note);
        refund=mTickets.get(position).getUUrefund_rule();
        Log.d("refund",refund);
        UUrefund_audit=mTickets.get(position).getUUrefund_audit();
        if("0".equals(preDaysNum)){
            mPayTimeTextView.setText("随时购买");
        }else{
            mPayTimeTextView.setText("需"+preDaysNum+"天前购买,"+"当日"+preHours+"都可以使用");
        }
        if("0".equals(delayType)){
            mPeriodOfValidatyTextView.setText("游玩日期当天起效");
        }else if("1".equals(delayType)){
            mPeriodOfValidatyTextView.setText("下单日期起有效");
        }else{
            mPeriodOfValidatyTextView.setText("期票模式");
        }


        mScenicIllustrateTextView.setText(note);
        if(refund!=null&&"0".equals(refund)){
            if("0".equals(UUrefund_audit)){
                mRefundTextView.setText("游玩日期内可退");
            }else{
                mRefundTextView.setText("游玩日期内可退,退票需审核");
            }
        }else if("1".equals(refund)){
            if("0".equals(UUrefund_audit)){
                mRefundTextView.setText("游玩日期前可退需在验证截止时间前退");
            }else{
                mRefundTextView.setText("游玩日期前可退需在验证截止时间前退,退票需审核");
            }
        }else if("2".equals(refund)){
            mRefundTextView.setText("不可退");
        }else{
            mRefundTextView.setText("暂无相关信息");
        }


            cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                final WindowManager.LayoutParams dismissparams = getWindow().getAttributes();
                dismissparams.alpha = 1.0f;
                getWindow().setAttributes(dismissparams);
            }
        });


    }

    private class ScenicDetailAdapter extends RecyclerView.Adapter<ScenicDetailViewHolder>{
        private ScenicDetailsActivity mOnRecyclerViewItemClickListener;
        private ScenicDetailsActivity mOnTicketListener;

        @Override
        public ScenicDetailViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(ScenicDetailsActivity.this);
            View view = layoutInflater.inflate(R.layout.scenic_ticket_order_recycle, parent, false);
            return new ScenicDetailViewHolder(view);

        }

        @Override
        public void onBindViewHolder(ScenicDetailViewHolder holder, final int position) {
            Ticket ticket = mTickets.get(position);
            holder.bindData(ticket);
            holder.mOrderTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnRecyclerViewItemClickListener.onClickInnerCtrl(position);
                }
            });
            holder.mMakeUseOfTicketTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnTicketListener.onClickTicket(position);
                }
            });

        }

        @Override
        public int getItemCount() {
            return mTickets.size();
        }

        public void setmOnRecyclerViewItemClickListener(ScenicDetailsActivity mOnRecyclerViewItemClickListener) {
            this.mOnRecyclerViewItemClickListener = mOnRecyclerViewItemClickListener;
        }
        public void setmOnTicketListener(ScenicDetailsActivity mOnTicketListener){
            this.mOnTicketListener=mOnTicketListener;
        }
    }

    private class ScenicDetailViewHolder extends RecyclerView.ViewHolder {
        private TextView mTicketTypeTextView;
        private TextView mTicketPriceTextView;
        private TextView mMakeUseOfTicketTextView;
        private TextView mOrderTextView;
        public ScenicDetailViewHolder(View itemView) {
            super(itemView);
            mTicketTypeTextView=(TextView)itemView.findViewById(R.id.textView_type);
            mTicketPriceTextView=(TextView)itemView.findViewById(R.id.textView_ticket_price);
            mMakeUseOfTicketTextView=(TextView)itemView.findViewById(R.id.textView_info);
            mOrderTextView=(TextView)itemView.findViewById(R.id.textView_order_ticket1);
        }
        public void bindData(Ticket ticket) {
            mTicketTypeTextView.setText(ticket.getUUtitle());
            ticketPrice=ticket.getRetail_price();
            mTicketPriceTextView.setText("¥"+ ToolUtil.fen2Yuan(ticketPrice));
            String preDays=ticket.getUUddays();
            String preHours=ticket.getUUdhour();
            if(preDays.equals("0")){
                mMakeUseOfTicketTextView.setText("随时购买，当日"+preHours+"前都可以使用");
            }else{
                mMakeUseOfTicketTextView.setText("需"+preDays+"天前购买，当日"+preHours+"前都可以使用");
            }
            mOrderTextView.setText("预订");
            mOrderTextView.setBackgroundResource(R.drawable.custom_button_yellow_pre);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        WindowManager.LayoutParams params=getWindow().getAttributes();
        params.alpha=1.0f;
        getWindow().setAttributes(params);
        return super.onTouchEvent(event);
    }
}
